using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using WebAuth.Bussiness;

namespace WebAuth.Models
{
    public abstract class AuthModel : IDbEntity
    {
        public string Id { get; set; }
        public string Name { get; set; }

        [NotMapped]
        public IList AuthChildren
        {
            get => _authChildren;
        }

        private IList _authChildren;
        public string AuthChildrenIds { get; set; }

        // TAuthChildren 需要作为子项进行关联的权限类对象。
        public virtual void SetAuthChildren<TAuthChildren>() where TAuthChildren : IDbEntity
        {
            CacheManager.GetCacheManager().GetModelSet(out Dictionary<string, TAuthChildren> authChildrenCacheSet);
            if (authChildrenCacheSet != null)
            {
                _authChildren = new List<TAuthChildren>();
                if (string.IsNullOrEmpty(AuthChildrenIds))
                {
                    return;
                }

                foreach (var authChildId in AuthChildrenIds.Split(","))
                {
                    if (authChildrenCacheSet.ContainsKey(authChildId))
                    {
                        _authChildren.Add(authChildrenCacheSet[authChildId]);
                    }
                }

                CacheManager.GetCacheManager().ChangeAutchCacheVer();
            }
            else
            {
                throw new Exception("权限子项尚未加载成功！");
            }
        }
    }
}